package cn.yunyichina.scheduler.jobs.service.register.impl;

import cn.yunyichina.provider.framework.dubbo.service.BaseService;
import cn.yunyichina.provider.framework.dubbo.service.OrderService;
import cn.yunyichina.provider.framework.dubbo.service.RegisterService;
import cn.yunyichina.provider.iface.entity.base.HospitalOutVo;
import cn.yunyichina.provider.iface.entity.base.OrderExceptionVo;
import cn.yunyichina.provider.iface.entity.base.OrderExtVo;
import cn.yunyichina.provider.iface.entity.base.Rule;
import cn.yunyichina.provider.iface.entity.common.Response;
import cn.yunyichina.provider.iface.entity.order.OrderRegSchedulerVo;
import cn.yunyichina.scheduler.jobs.service.register.RegisterUnlockService;
import cn.yunyichina.utils.commons.DateUtils;
import cn.yunyichina.utils.convert.JsonUtils;
import com.alibaba.fastjson.JSON;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2017/5/3.
 */
@Service
public class RegisterUnlockServiceImpl implements RegisterUnlockService {

    private static final Logger logger = LoggerFactory.getLogger(RegisterUnlockServiceImpl.class);
    @Override
    public void doExecute() {

        //查询缓存中所有的医院
        Response hospitalResp =  BaseService.callUnderlineFromInternal("yyt.base.hospital.by.app.code.list","{\"app_code\":\"all\"}");
        if (!"0".equals(hospitalResp.getResultCode())) {
            logger.error("doExecute, 查询缓存医院失败 app_code=all");
            return ;
        }
        List<HospitalOutVo> hospitalOutVoList = JsonUtils.parseArray(hospitalResp.getResult(),HospitalOutVo.class);
        for(HospitalOutVo hospital:hospitalOutVoList){
            String orgCode = hospital.getHospitalCode();
            Map<String,String> map = new HashedMap();
            map.put("attribute_name" , "paymentTimeOutTime");
            map.put("org_code" , orgCode);
            Response ruleResp = BaseService.callHumpFromInternal("yyt.base.rule.select", JSON.toJSONString(map));//RegisterService.callUnderlineFromInternal("yyt.register.reg.cache.rule.get","{\"org_code\":\""+ orgCode +"\"}");
            if (!"0".equals(ruleResp.getResultCode())) {
                logger.error("doExecute, 查询缓存规则失败：" + orgCode );
                continue;
            }
            Rule rule=JsonUtils.parseObject(ruleResp.getResult(), Rule.class);
            String paymentTimeOutTime = "30";//支付超时默认30分钟
            if(rule != null){
                paymentTimeOutTime = rule.getAttributeProperties();
                paymentTimeOutTime = String.valueOf(Integer.parseInt(paymentTimeOutTime) + 4);
            }

            //开始查询超时订单
            OrderExtVo query = new OrderExtVo();
            query.setOrderTypeRegister();
            query.setOrgCode(orgCode);
            query.setPayStatusAccess();
            query.setOrderStatusCreate();
            Date now_30 = new Date(System.currentTimeMillis() - Integer.parseInt(paymentTimeOutTime)*60*1000);//超时之前的时间
            String endTime = DateUtils.dateToString(now_30);
            query.setBeginCreatedTime(DateUtils.getDateStr(new Date()) + " 00:00:00");//加上查询一天范围内的订单
            query.setEndCreatedTime(endTime);
            Response response = BaseService.callUnderlineFromInternal("yyt.base.order.list",
                    JsonUtils.toJsonString(query));
            logger.info("RegisterUnlockService doExecute, yyt.base.order.list response=" + JSON.toJSONString(response));
            if (!"0".equals(response.getResultCode())) {
                logger.error("doExecute, 查询订单失败");
                continue ;
            }

            List<OrderExtVo> vos = JsonUtils.parseArray(response.getResult(), OrderExtVo.class);
            if(CollectionUtils.isEmpty(vos)){
                logger.info("doExecute, 查询不到超时未支付的订单,医院：" + orgCode);
                continue;
            }
            for(OrderExtVo order:vos){
                if(StringUtils.isNotBlank(order.getReserveNo())){
                    logger.info("RegisterUnlockService doExecute,有预约号码，不解锁，预约号=" + order.getReserveNo());
                    continue;
                }
                try {
                    String data = "{\"order_no\":\"" + order.getOrderNo() + "\"}";
                    Response unlocdResp =  RegisterService.callUnderlineFromInternal("yyt.register.reg.record.unlock",data);
                    logger.info("RegisterUnlockService doExecute, yyt.register.reg.record.unlock response=" + JSON.toJSONString(unlocdResp));

                    //添加到中间表
                    OrderRegSchedulerVo schedulerVo = parseOrder(order);
                    schedulerVo.setOrderStatus(OrderExtVo.ORDER_STATUS_CANCEL);
                    schedulerVo.setStopStatus((short) 0);//停诊状态，非停诊
                if("0".equals(unlocdResp.getResultCode())){
                    logger.info("RegisterUnlockService doExecute, 成功解锁，订单号：" + order.getOrderNo());
                        schedulerVo.setUnlockResult((short) 1);
                    } else {
                        schedulerVo.setUnlockResult((short) 2);
                    }
                    schedulerVo.setUnlockCount((short) 1);
                    OrderService.getOrderClient().addOrderRegScheduler(schedulerVo);//加到定时任务中间表
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }

    }


    /**
     * 转换成订单定时任务中间表实体
     *
     * @param order
     * @return
     */
    private OrderRegSchedulerVo parseOrder(OrderExtVo order) {
        OrderRegSchedulerVo vo = new OrderRegSchedulerVo();
        vo.setId(order.getId());
        vo.setOrgCode(order.getOrgCode());
        vo.setOrgName(order.getOrgName());
        vo.setOrderNo(order.getOrderNo());
        vo.setBranchCode(order.getBranchCode());
        vo.setDoctorName(order.getDoctorName());
        vo.setDeptName(order.getDeptName());
        vo.setPlatformOrgAppCode(order.getPlatformOrgAppCode());
        vo.setUserName(order.getUserName());
        vo.setUserMobile(order.getUserMobile());
        vo.setOpenId(order.getOpenId());
        vo.setScheduleTime(order.getScheduleTime());
        vo.setIsInsurance(order.getIsInsurance());
        vo.setHisOrderNo(order.getHisOrderNo());
        vo.setPayMode(order.getPayMode());
        vo.setOrderStatus(order.getOrderStatus());
        vo.setPayStatus(order.getPayStatus());
        vo.setTotalAmount(order.getTotalAmount());
        vo.setPayAmount(order.getPayAmount());
        vo.setPaymentDealId(order.getPaymentDealId());
        vo.setCreatedTime(order.getCreatedTime());

        Map<String, Object> extraParams = JsonUtils.parseObject(order.getExtraParams(), Map.class);
        String beginTime = "00:00", endTime = "23:59";
        if (extraParams != null) {
            beginTime = (String) extraParams.get("begin_time");
            endTime = (String) extraParams.get("end_time");
        }
        vo.setBeginTime(beginTime);
        vo.setEndTime(endTime);
        vo.setCancelSerialNo((String) extraParams.get("cancel_serial_no"));
        vo.setCancelBillNo((String) extraParams.get("cancel_bill_no"));
        return vo;
    }
}
